package com.spdzen.controller.admin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spdzen.model.SysUser;
import com.spdzen.service.SysUserService;
import com.spdzen.support.JsonUtils;
import com.spdzen.support.LogUtils;
import com.spdzen.support.PageOffsetParam;
import com.spdzen.support.UploadFileUtils;
import com.spdzen.support.ValidateUtils;
import com.spdzen.support.exception.ResultCodeException;
import com.spdzen.support.result.JsonResult;
import com.spdzen.support.validation.AddValidGroup;
import com.spdzen.support.validation.UpdateValidGroup;
import com.spdzen.vo.search.SysUserAdminSearch;

@Controller
@RequestMapping("/admin/sysuser")
public class SysUserAdminController {
	@Resource
	private SysUserService sysUserService;

	@RequestMapping("/pageView.do")
	public String pageView() {
		return "/admin/sysuser/sysUserPageView";
	}

	@RequestMapping("/queryPage.do")
	@ResponseBody
	public JsonResult queryPage(PageOffsetParam param, SysUserAdminSearch search) {
		try {
			return JsonResult.success(sysUserService.selectPage(param, search));
		} catch (Exception e) {
			LogUtils.getLogger().error(JsonUtils.toJSONString(param, search), e);
			return JsonResult.error();
		}
	}

	@RequestMapping("/add.do")
	@ResponseBody
	public JsonResult add(@Validated(value = { AddValidGroup.class }) SysUser entity, BindingResult bindingResult, HttpServletRequest request) {
		if(bindingResult.hasErrors()) {
			return JsonResult.errorParameter();
		}
		
		JsonResult jsonResult = null;
		try {
			if(StringUtils.isNotBlank(entity.getHeadimgurl())){
				entity.setHeadimgurl(UploadFileUtils.copyToAdminAvatar(request, entity.getHeadimgurl()));
			}
			
			sysUserService.inserIfPermission(entity);
			jsonResult = JsonResult.success();
		} catch (ResultCodeException e) {
			jsonResult = new JsonResult(e.getResultCode());
		} catch (Exception e) {
			LogUtils.getLogger().error(JsonUtils.toJSONString(entity), e);
			jsonResult = JsonResult.error();
		}
		
		return jsonResult;
	}
	
	@RequestMapping("/update.do")
	@ResponseBody
	public JsonResult update(@Validated(value = { UpdateValidGroup.class }) SysUser entity, BindingResult bindingResult, HttpServletRequest request) {
		if(bindingResult.hasErrors()) {
			return JsonResult.errorParameter();
		}
		
		try {
			SysUser record = sysUserService.selectById(entity.getId());
			if(record == null){
				return JsonResult.error("用户不存在！");
			}
			
			boolean changeAvatar = StringUtils.isNotBlank(entity.getHeadimgurl()) && !entity.getHeadimgurl().equalsIgnoreCase(record.getHeadimgurl());			
			
			if(changeAvatar) {
				entity.setHeadimgurl(UploadFileUtils.copyToAdminAvatar(request, entity.getHeadimgurl()));
			}
			
			sysUserService.updateIfPermission(entity);
			
			if(changeAvatar && StringUtils.isNotBlank(record.getHeadimgurl())) {
				try {
					UploadFileUtils.deleteFile(request, record.getHeadimgurl());
				} catch (Exception e) {
				}
			}
			
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.getLogger().error(JsonUtils.toJSONString(entity), e);
			return JsonResult.error();
		}
	}
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public JsonResult delete(Long id, HttpServletRequest request) {
		if(id == null || id.longValue() < 1) {
			return JsonResult.errorParameter();
		}
		
		try {
			SysUser record = sysUserService.selectById(id);
			if(record == null){
				return JsonResult.error("用户不存在！");
			}
			
			sysUserService.deleteIfPermission(id);
			
			if(StringUtils.isNotBlank(record.getHeadimgurl())){
				try {
					UploadFileUtils.deleteFile(request, record.getHeadimgurl());
				} catch (Exception e) {
				}
			}
			
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.getLogger().error(id.toString(), e);
			return JsonResult.error();
		}
	}
	
	@RequestMapping("/resetPwd.do")
	@ResponseBody
	public JsonResult delete(Long id, String password, HttpServletRequest request) {
		if(id == null || id.longValue() < 1 || !ValidateUtils.rangeLength(password, 6, 30)) {
			return JsonResult.errorParameter();
		}
		
		try {
			sysUserService.changePassword(id, password);
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.getLogger().error(id.toString(), e);
			return JsonResult.error();
		}
	}
}
